using UnityEngine;
using System.Collections;
using QFramework;
using Cysharp.Threading.Tasks;
using DG.Tweening;
using Sirenix.OdinInspector;
using UnityEngine.SceneManagement;

public class Mosaic : PostEffectsBase,IController
{
	public Shader mosaicShader;
	private Material mosaicMaterial = null;
	public Material material 
	{  
		get {
			mosaicMaterial = CheckShaderAndCreateMaterial(mosaicShader, mosaicMaterial);
			return mosaicMaterial;
		}  
	}
	public float mask = 1;
    public float mosaic = 200;

	public bool gameOver = false;
	public bool gameFail = false;
	private void Start()
	{
		
	}

	public void OnGameOver(GameOver gameOverEvent)
	{
		gameOver = true;
		if(gameOverEvent.isSuccess == false)
		{
			gameFail = true;
			OnFail().Forget();
		}
	}


	void OnEnable() 
	{
		GetComponent<Camera>().depthTextureMode |= DepthTextureMode.DepthNormals;
	}

	private async UniTaskVoid OnFail() 
	{
		await DOTween.To(()=> mosaic,x => mosaic = x,1,3);
		await DOTween.To(()=> mask,x => mask = x,0,2);
		this.GetModel<StageModel>().needChange2Win = false;
		await this.GetSystem<UIManager>().OpenUIPanel("UIPanel/UIGameOver/UIGameFail");
		SceneManager.LoadScene("StartScene");
	}

	[ImageEffectOpaque]
	void OnRenderImage (RenderTexture src, RenderTexture dest) 
	{
		if (material != null && gameOver == true && gameFail == true) 
		{
			material.SetFloat("_Mosaic", mosaic);
			material.SetFloat("_Mask", mask);
			Graphics.Blit(src, dest, material,0);
		} else {
			Graphics.Blit(src, dest);
		}
	}

    public IArchitecture GetArchitecture() => GameArchitecture.Interface;
}
